package com.deyinet.bdcms.dao.impl;

import com.deyinet.bdcms.core.dao.impl.BaseDaoImpl;
import com.deyinet.bdcms.dao.IDeviceDao;
import com.deyinet.bdcms.entity.Device;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.*;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

/**
 * Created by Bacel on 2017/04/16.
 */
@Repository
public class DeviceDao extends BaseDaoImpl<Device> implements IDeviceDao {

    @Override
    public List<Device> findMapDevice(Device example) {
        Criteria criteria = this.getSession().createCriteria(this.clazz);
        criteria.add(Example.create(example).enableLike(MatchMode.ANYWHERE));
        return criteria.list();
    }

    @Override
    public List<Device> findByExampleLikeImport(Device example) {
        Criteria criteria = this.getSession().createCriteria(this.clazz);
        criteria.add(Example.create(example).enableLike(MatchMode.ANYWHERE));
        if (example.getDeviceownerByOwnerid()!=null){
            criteria.createAlias("deviceownerByOwnerid", "owner");
            criteria.add(Restrictions.like("owner.name", "%"+example.getDeviceownerByOwnerid().getName()+"%"));
        }
        return criteria.list();
    }

    @Override
    public List<Device> findByExampleLike(Device example, int pageNo, int pageSize) {
        Criteria criteria = this.getSession().createCriteria(this.clazz);
        criteria.add(Example.create(example).enableLike(MatchMode.ANYWHERE));
        if (example.getDeviceownerByOwnerid()!=null){
            criteria.createAlias("deviceownerByOwnerid", "owner");
            criteria.add(Restrictions.like("owner.name", "%"+example.getDeviceownerByOwnerid().getName()+"%"));
        }
        return createPageOrder(criteria, pageNo, pageSize, Order.desc("id")).list();
    }

    @Override
    public long countByExampleLike(Device example) {
        Criteria criteria = getSession().createCriteria(this.clazz);
        criteria.add(Example.create(example).enableLike(MatchMode.ANYWHERE));
        if (example.getDeviceownerByOwnerid()!=null){
            criteria.createAlias("deviceownerByOwnerid","owner");
            criteria.add(Restrictions.like("owner.name", "%"+example.getDeviceownerByOwnerid().getName()+"%"));
        }
        Long o = (Long)criteria.setProjection(Projections.count("id")).uniqueResult();
        return o.longValue();
    }
    @Override
    public void batchDelete(Serializable[] ids){
        String hql = "";
        for(int i=0;i<ids.length;i++) {
            if(i==0) {
                hql = "sn='"+ids[i]+"'";
            } else {
                hql =hql + " or sn='"+ids[i]+"'";
            }
        }
        Session session= this.getSession();
        Query q= session.createQuery("delete from "+clazz.getName()+" where "+hql);
        q.executeUpdate();
    }
}